package controllers.product;

import java.io.File;
import java.util.Date;

import models.Category;
import models.Comment;
import models.OrderItem;
import models.Product;
import play.Play;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Http.MultipartFormData;
import play.mvc.Http.MultipartFormData.FilePart;
import play.mvc.Result;
import views.html.home;

import com.avaje.ebean.Ebean;
import com.avaje.ebean.Junction;
import com.avaje.ebean.Page;

import controllers.routes;
import controllers.buy.CartController;
import controllers.user.UserController;

public class ProductController extends Controller {

	static Form<Product> productForm = form(Product.class);
	static Form<OrderItem> orderItemForm = form(OrderItem.class);
	static Form<Comment> commentForm = form(Comment.class);

	public static Result list(int page,int catid, String order) {
		 	return ok(
		            views.html.product.list.render(page(4, page, catid),catid,order));
	}

	/*public static Result products() {
		return ok(views.html.product.products.render(Category.rootCategories(),
				null));
	}*/

	public static Result info(Long id) {
		orderItemForm.data().put("amount", "1");
		return ok(views.html.product.info.render(Ebean.find(Product.class, id),
				CommentController.getList(id), orderItemForm, commentForm));
	}

	public static Result addComment(Long id) {
		Form<Comment> filledForm = commentForm.bindFromRequest();
		Comment c = new Comment();
		c.setText(filledForm.get().getText());
		c.setDate(new Date());
		c.setUser(UserController.getCurrentUser());
		c.setProduct(Ebean.find(Product.class, id));
		c.save();
		// return ok(views.html.index.render(c.toString()));
		return redirect(controllers.product.routes.ProductController.info(id));
	}

	public static Result addToCart(Long id) {
		Form<OrderItem> filledForm = orderItemForm.bindFromRequest();
		if (filledForm.hasErrors()) {
			return badRequest(views.html.product.info.render(
					Ebean.find(Product.class, id), null, filledForm,
					commentForm)); // TODO Comment.getList

		} else if (filledForm.get().getAmount() < 1) {
			return CartController.create(Ebean.find(Product.class, id), 1);
		} else {
			return CartController.create(Ebean.find(Product.class, id),
					filledForm.get().getAmount());
		}

	}

	public static Result newProduct() {
		if (UserController.getCurrentUser().getPriv("worker")) {
			return ok(views.html.product.upload.render(productForm,
					Category.rootCategories()));
		}
		return redirect(routes.Application.index());
	}

	public static Result delete(Long id) {
		Product p = Ebean.find(Product.class, id);
		Long cid = p.getCategory().getId();
		Product.delete(id);
		return redirect(controllers.product.routes.ProductController.list(0,Integer.parseInt(cid.toString()),"asc"));
	}

	public static Result upload() {

		Form<Product> filledForm = productForm.bindFromRequest();

		if (filledForm.hasErrors()) {
			return badRequest(views.html.product.upload.render(filledForm,
					Category.find.all()));
		} else {

			Product p = filledForm.get();

			p.setCategory(Ebean.find(Category.class,
					filledForm.data().get("category_id")));

			MultipartFormData body = request().body().asMultipartFormData();
			FilePart picture = body.getFile("photo");

			// String contentType;

			if (picture == null) {
				p.setPhoto("example.png");
			} else {
				String fileName = picture.getFilename();
				// contentType = picture.getContentType();
				File file = picture.getFile();
				file.renameTo(new File(Play.application().path()
						+ "\\public\\images\\product\\" + fileName));
				p.setPhoto(fileName);
			}

			Product.create(p);
			return redirect(controllers.product.routes.ProductController.list(0,Integer.parseInt(p
					.getCategory().getId().toString()),"asc"));
			// return redirect(routes.Application.index());
		}
	}

	public static Result search(String query) {

		String[] queries = query.split("\\s");

		Junction<Product> junction = Product.find.where()
				.like("type", "product").disjunction();

		for (String expr : queries) {

			String searchExpression = "%" + expr + "%";

			junction.like("name", searchExpression).like("description",
					searchExpression);
		}
		return ok(views.html.product.search.render(query, junction
				.endJunction().findList()));
	}

	public static Page<Product> page(int pageSize, int page,int cat) {
	    if(cat==0)
		return Ebean.find(Product.class).where().like("type", "product")
		// .orderBy(order)
				.findPagingList(pageSize).getPage(page);
		// return
		// Product.("select * form product where product?(select product_id from  from Product where ");
		/*
		 * return ok( mostList.render( Product.page(page, 10, sortBy, order,
		 * filter), sortBy, order, filter ) ); }
		 */
	    else
		return Ebean.find(Product.class).where().like("type", "product").eq("category_id", cat)
			// .orderBy(order)
					.findPagingList(pageSize).getPage(page);
	}
}
